//
//  SocialMediaManager.swift
//  CMB250716
//
//  Created by Trae AI on 2024/12/19.
//

import Foundation
import SwiftUI

// MARK: - Configuration
struct SocialMediaConfig {
    static let likeSharePoints = 2
    static let originalPoints = 10
    static let dailyPointsLimit = 45
    static let monthlyPointsLimit = 800
    
    struct Strings {
        static let dailyPointsExceeded = [
            "zh": "今日积分已达上限",
            "en": "Daily points limit reached"
        ]
        
        static let monthlyPointsExceeded = [
            "zh": "本月积分已达上限",
            "en": "Monthly points limit reached"
        ]
        
        static let submissionSuccess = [
            "zh": "提交成功，等待审核",
            "en": "Submission successful, pending review"
        ]
    }
}

// MARK: - Enums
enum SocialPlatform: String, CaseIterable {
    case weibo = "weibo"
    case wechat = "wechat"
    case douyin = "douyin"
    case xiaohongshu = "xiaohongshu"
    case instagram = "instagram"
    case facebook = "facebook"
    case twitter = "twitter"
    case tiktok = "tiktok"
    case youtube = "youtube"
    case google = "google"
    case others = "others"
    
    func localizedName(language: String) -> String {
        switch self {
        case .weibo:
            return language == "zh" ? "微博" : "Weibo"
        case .wechat:
            return language == "zh" ? "微信" : "WeChat"
        case .douyin:
            return language == "zh" ? "抖音" : "Douyin"
        case .xiaohongshu:
            return language == "zh" ? "小红书" : "Xiaohongshu"
        case .instagram:
            return "Instagram"
        case .facebook:
            return "Facebook"
        case .twitter:
            return "Twitter"
        case .tiktok:
            return "TikTok"
        case .youtube:
            return "YouTube"
        case .google:
            return "Google"
        case .others:
            return language == "zh" ? "其他" : "Others"
        }
    }
    
    var officialURL: String {
        switch self {
        case .instagram:
            return "https://www.instagram.com/cumrbull/"
        case .tiktok:
             return "https://www.tiktok.com/@cumrbull"
         case .youtube:
             return "https://www.youtube.com/@cumrbull"
         case .facebook:
             return "https://www.facebook.com/cumrbull"
        case .xiaohongshu:
            return "https://www.xiaohongshu.com/user/profile/cumrbull"
        case .weibo:
            return "https://weibo.com/cumrbull"
        default:
            return "https://www.cumrbull.com"
        }
    }
    
    var iconName: String {
        switch self {
        case .instagram:
            return "Instagram_Icon"
        case .tiktok:
             return "TikTok_Icon"
         case .youtube:
             return "YouTube_Icon"
         case .facebook:
             return "Facebook_Icon"
        case .xiaohongshu:
            return "Xiaohongshu_Icon"
        default:
            return "Logo"
        }
    }
}

enum InteractionType: String, CaseIterable, Codable {
    case like = "like"
    case share = "share"
    case original = "original"
    
    var points: Int {
        switch self {
        case .like, .share:
            return SocialMediaConfig.likeSharePoints
        case .original:
            return SocialMediaConfig.originalPoints
        }
    }
    
    var icon: String {
        switch self {
        case .like:
            return "heart.fill"
        case .share:
            return "arrowshape.turn.up.right.fill"
        case .original:
            return "pencil.and.outline"
        }
    }
    
    var color: Color {
        switch self {
        case .like:
            return Color.red
        case .share:
            return Color.blue
        case .original:
            return Color.green
        }
    }
    
    func localizedName(language: String) -> String {
        switch self {
        case .like:
            return language == "zh" ? "点赞" : "Like"
        case .share:
            return language == "zh" ? "转发" : "Share"
        case .original:
            return language == "zh" ? "原创" : "Original"
        }
    }
    
    func localizedDescription(language: String) -> String {
        switch self {
        case .like:
            return language == "zh" ? "为他人内容点赞" : "Like others' content"
        case .share:
            return language == "zh" ? "转发分享内容" : "Share content"
        case .original:
            return language == "zh" ? "发布原创内容" : "Post original content"
        }
    }
}

enum SubmissionStatus: String, CaseIterable, Codable {
    case pending = "pending"
    case approved = "approved"
    case rejected = "rejected"
}

// MARK: - Data Models
struct SocialMediaSubmission: Identifiable, Codable {
    let id: UUID
    let userId: String
    let platform: String
    let interactionType: InteractionType
    let description: String
    let link: String?
    let imageData: Data?
    let submissionDate: Date
    let pointsAwarded: Int
    var status: SubmissionStatus
    
    init(userId: String, platform: String, interactionType: InteractionType, description: String, link: String? = nil, imageData: Data? = nil) {
        self.id = UUID()
        self.userId = userId
        self.platform = platform
        self.interactionType = interactionType
        self.description = description
        self.link = link
        self.imageData = imageData
        self.submissionDate = Date()
        self.pointsAwarded = interactionType.points
        self.status = .pending
    }
    
    func getDisplayTitle(language: String) -> String {
        let platformName = SocialPlatform(rawValue: platform)?.localizedName(language: language) ?? platform
        let interactionName = interactionType.localizedName(language: language)
        return "\(platformName) - \(interactionName)"
    }
}

struct UserPointsStats {
    let daily: Int
    let monthly: Int
}

// MARK: - Social Media Manager
class SocialMediaManager: ObservableObject {
    
    // MARK: - Social Media Platforms for Home Page
     static let homePagePlatforms: [SocialPlatform] = [
         .instagram, .tiktok, .youtube, .facebook, .xiaohongshu
     ]
    
    static func openSocialMedia(platform: SocialPlatform) {
        guard let url = URL(string: platform.officialURL) else { return }
        
        if UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url)
        }
    }
    @Published var submissions: [SocialMediaSubmission] = []
    
    private let userDefaults = UserDefaults.standard
    private let submissionsKey = "social_media_submissions"
    private let rulesReadKey = "social_media_rules_read"
    
    init() {
        loadData()
        setupSampleData()
    }
    
    // MARK: - Data Management
    private func saveData() {
        if let encoded = try? JSONEncoder().encode(submissions) {
            userDefaults.set(encoded, forKey: submissionsKey)
        }
    }
    
    private func loadData() {
        if let data = userDefaults.data(forKey: submissionsKey),
           let decoded = try? JSONDecoder().decode([SocialMediaSubmission].self, from: data) {
            submissions = decoded
        }
    }
    
    private func setupSampleData() {
        guard submissions.isEmpty else { return }
        
        let sampleSubmissions = [
            SocialMediaSubmission(
                userId: "sample_user_1",
                platform: "weibo",
                interactionType: .like,
                description: "为朋友的旅行照片点赞"
            ),
            SocialMediaSubmission(
                userId: "sample_user_1",
                platform: "wechat",
                interactionType: .original,
                description: "分享了一篇关于健康生活的原创文章"
            ),
            SocialMediaSubmission(
                userId: "sample_user_1",
                platform: "douyin",
                interactionType: .share,
                description: "转发了一个有趣的短视频"
            )
        ]
        
        submissions = sampleSubmissions
        saveData()
    }
    
    // MARK: - Public Methods
    func submitEvidence(userId: String, platform: String, interactionType: InteractionType, description: String, link: String? = nil, imageData: Data? = nil, language: String = "zh") -> (success: Bool, message: String) {
        
        // Check daily points limit
        let dailyPoints = getUserPointsStats(userId: userId).daily
        if dailyPoints + interactionType.points > SocialMediaConfig.dailyPointsLimit {
            return (false, SocialMediaConfig.Strings.dailyPointsExceeded[language] ?? "Daily points limit reached")
        }
        
        // Check monthly points limit
        let monthlyPoints = getUserPointsStats(userId: userId).monthly
        if monthlyPoints + interactionType.points > SocialMediaConfig.monthlyPointsLimit {
            return (false, SocialMediaConfig.Strings.monthlyPointsExceeded[language] ?? "Monthly points limit reached")
        }
        
        let submission = SocialMediaSubmission(
            userId: userId,
            platform: platform,
            interactionType: interactionType,
            description: description,
            link: link,
            imageData: imageData
        )
        
        submissions.append(submission)
        saveData()
        
        return (true, SocialMediaConfig.Strings.submissionSuccess[language] ?? "Submission successful, pending review")
    }
    
    func addPoints(userId: String, points: Int) -> Bool {
        let currentStats = getUserPointsStats(userId: userId)
        
        // Check if adding points would exceed limits
        if currentStats.daily + points > SocialMediaConfig.dailyPointsLimit {
            return false
        }
        
        if currentStats.monthly + points > SocialMediaConfig.monthlyPointsLimit {
            return false
        }
        
        return true
    }
    
    func getUserSubmissions(userId: String) -> [SocialMediaSubmission] {
        return submissions.filter { $0.userId == userId }.sorted { $0.submissionDate > $1.submissionDate }
    }
    
    func getUserPointsStats(userId: String) -> UserPointsStats {
        let userSubmissions = submissions.filter { $0.userId == userId && $0.status == .approved }
        
        let calendar = Calendar.current
        let now = Date()
        
        let dailyPoints = userSubmissions
            .filter { calendar.isDate($0.submissionDate, inSameDayAs: now) }
            .reduce(0) { $0 + $1.pointsAwarded }
        
        let monthlyPoints = userSubmissions
            .filter {
                let components = calendar.dateComponents([.year, .month], from: $0.submissionDate)
                let nowComponents = calendar.dateComponents([.year, .month], from: now)
                return components.year == nowComponents.year && components.month == nowComponents.month
            }
            .reduce(0) { $0 + $1.pointsAwarded }
        
        return UserPointsStats(daily: dailyPoints, monthly: monthlyPoints)
    }
    
    func canSubmit(userId: String, interactionType: InteractionType) -> Bool {
        let currentStats = getUserPointsStats(userId: userId)
        
        // Check if adding points would exceed daily limit
        if currentStats.daily + interactionType.points > SocialMediaConfig.dailyPointsLimit {
            return false
        }
        
        // Check if adding points would exceed monthly limit
        if currentStats.monthly + interactionType.points > SocialMediaConfig.monthlyPointsLimit {
            return false
        }
        
        return true
    }
    
    func canSubmit(userId: String) -> (success: Bool, message: String) {
        let currentStats = getUserPointsStats(userId: userId)
        
        // Check if user has reached daily limit with minimum points (like/share = 2 points)
        if currentStats.daily + SocialMediaConfig.likeSharePoints > SocialMediaConfig.dailyPointsLimit {
            return (false, SocialMediaConfig.Strings.dailyPointsExceeded["zh"] ?? "Daily points limit reached")
        }
        
        // Check if user has reached monthly limit with minimum points
        if currentStats.monthly + SocialMediaConfig.likeSharePoints > SocialMediaConfig.monthlyPointsLimit {
            return (false, SocialMediaConfig.Strings.monthlyPointsExceeded["zh"] ?? "Monthly points limit reached")
        }
        
        return (true, "")
    }
    
    func resetDailyData() {
        // No daily submission counts to reset anymore
        // Daily points are calculated dynamically based on submission dates
    }
    
    func resetMonthlyData() {
        // No monthly submission counts to reset anymore
        // Monthly points are calculated dynamically based on submission dates
    }
    
    // MARK: - Rules Management
    func hasUserReadRules(userId: String) -> Bool {
        let readUsers = userDefaults.array(forKey: rulesReadKey) as? [String] ?? []
        return readUsers.contains(userId)
    }
    
    func markUserAsReadRules(userId: String) {
        var readUsers = userDefaults.array(forKey: rulesReadKey) as? [String] ?? []
        if !readUsers.contains(userId) {
            readUsers.append(userId)
            userDefaults.set(readUsers, forKey: rulesReadKey)
        }
    }
}